<template>
  <div>
    <a-tabs
      v-model:activeKey="activeKey"
      type="card"
    >
      <a-tab-pane
        key="1"
        tab="奖品列表"
      ></a-tab-pane>
      <a-tab-pane
        key="2"
        tab="设置抽奖积分"
      ></a-tab-pane>
    </a-tabs>

    <div
      class="set-box"
      v-if="activeKey == 2"
    >
      <div>抽奖消耗积分数量：</div>
      <a-input-number
        class="input-number-set"
        id="inputNumber"
        v-model:value="raffle"
        :min="1"
        :max="1000000"
      />

      <div>
        <a-button
          type="primary"
          @click="saveRaffle()"
        >
          确认
        </a-button>
      </div>
    </div>
    <template v-if="activeKey == 1">
      <div class="header-tool">
        <a-button v-if="pagination.total<=7"
          type="primary"
          @click="handleEdit()"
        >
          新增
        </a-button>
        <a-button
      class="mr10"
      type="primary"
      @click="reLoad()"
    >
      刷新
    </a-button>
      </div>

      <a-table
        :row-key="(record) => record.news_id"
        :rowSelection="{
          onChange: onSelectChange,

          selectedRowKeys: mapRows
        }"
        :columns="newColumns"
        :dataSource="activities"
           @change="handleTableChange"
        :pagination="
          isObject(pagination)
            ? {
                showQuickJumper: true,
                total: pagination.total,
                current: pagination.current,
                pageSize: pagination.pageSize,
                showTotal: (total) => `共计 ${pagination.total} 条`
              }
            : false
        "
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.dataIndex === 'prize_image'">
            <img
              style="width: 50px; height: 50px"
              :src="record.prize_image"
            />
          </template>
          <template v-if="column.dataIndex === 'del'">
            <a-switch
              @change="changeDel($event, record)"
              checked-children="上架"
              un-checked-children="下架"
              v-model:checked="record.del"
            />
          </template>

          <template v-if="column.dataIndex === 'action'">
            <span>
              <a @click="handleEdit(record)">编辑</a>
              <a-divider type="vertical" />
              <a-popconfirm
                class="gap-popconfirm"
                title="确定删除吗？"
                ok-text="确认"
                cancel-text="取消"
                @confirm="handleDelete(record)"
              >
                <a>删除</a>
              </a-popconfirm>
            </span>
          </template>
        </template>
      </a-table>
    </template>
    <raffleForm
      ref="newsFormEle"
      :showAddDialog="showAddDialog"
      @success="reload"
      @close="showAddDialog = false"
    />
  </div>
</template>

<script setup>
  import { isObject } from 'lodash-es'
  import { message } from 'ant-design-vue'

  import { ref, onMounted, reactive, computed } from 'vue'
  import { useRouter } from 'vue-router'
  import { ElButton, ElTable, ElTableColumn, ElDialog } from 'element-plus'
  import raffleForm from './raffleForm.vue'
  import { raffleList, raffleDel, raffleUpdate, rafflePoint } from '@/api/index'
  const pagination = reactive({
    current: 1,
    pageSize: 10,
    total: 0
  })
  const activeKey = ref('1')
  const raffle = ref(null)
  const activities = ref([])
  const newColumns = [
    // {
    //   title: 'id',
    //   dataIndex: 'raffle_id',
    //   key: 'ID'
    // },
    {
      title: '奖品名称',
      dataIndex: 'prize_name',
      key: 'prize_name'
    },
    {
      title: '奖品图片',
      dataIndex: 'prize_image',
      key: 'prize_image'
    },
    {
      title: '库存',
      dataIndex: 'stock',
      key: 'stock'
    },
    {
      title: '中奖概率',
      dataIndex: 'probability',
      key: 'probability'
    },
    {
      title: '上架',
      dataIndex: 'del',
      key: 'del'
    },
    {
      title: '创建时间',
      dataIndex: 'created_at',
      key: 'created_at'
    },
    {
      title: '操作',
      dataIndex: 'action',
      key: 'action'
    }
  ]
   
  const mapRows = ref([])
 
  const onSelectChange = (selectedRowKeys, selectedRows) => {
    mapRows.value = selectedRowKeys
  }
  const saveRaffle = () => {
    rafflePoint({
      point: raffle.value
    }).then((res) => {
      if(res.errorCode){
        message.error(res.msg||'操作失败')
        return
      }
      message.success('设置成功')
    })
  }
  const batchLoading = (status) => {
    if (mapRows.value.length == 0) {
      message.error('请选择要操作的项')
      return
    }
    console.log(mapRows.value)

    newsIsDestroy({ news_id: mapRows.value, is_del: status == 1 ? true : false }).then((res) => {
      if(res.errorCode){
        message.error(res.msg||'操作失败')
        return
      }
      getList()
    })
  }
  const newsFormEle = ref()
  const showAddDialog = ref(false)
  const router = useRouter()
  const isFetching = ref(false)
const probabilityTotal=ref(0)
  const getList = () => {
    raffleList({
      page: pagination.current,
      pageSize: pagination.pageSize
    })
      .then((res) => {
        if(res.errorCode){
        message.error(res.msg||'操作失败')
        return
      }
        activities.value = res.data
       
        if (res.data.length > 0) {
          raffle.value = res.data[0].point
        }
        pagination.total = res.total
      })
      .catch((err) => {
        console.log(err)
      })
  }
  getList()
  const reLoad = () => {
    pagination.current = 1
    getList()
  }
  const handleTableChange = ({ current, pageSize }) => {
    pagination.current = current
    pagination.pageSize = pageSize
    getList()
  }
  // 编辑
  const handleEdit = (row) => {
    showAddDialog.value = true 
 
    probabilityTotal.value=activities.value?.reduce((total,item)=>{
          return total+ Number(item.probability)
        },0)
        let canUse=100-probabilityTotal.value
    if(row){
      canUse=   100-probabilityTotal.value+  Number( row.probability)
      
    }
   
    newsFormEle.value.init(canUse, pagination.total,row)
  }
  const changeDel = (e, row) => {
    raffleUpdate({ raffle_id: row.raffle_id, del: e })
      .then((res) => {
        if(res.errorCode){
        message.error(res.msg||'操作失败')
        return
      }
        getList() // Refresh activity list after deletion
      })
      .catch((error) => {
        row.is_del = !e
      })
  }
  const handleDelete = (row) => {
    raffleDel({ raffle_id: row.raffle_id })
      .then((res) => {
        if(res.errorCode){
        message.error(res.msg||'操作失败')
        return
      }
        getList() // Refresh activity list after deletion
      })
      .catch((error) => {
        console.error('Error deleting activity:', error)
      })
  }

  const reload = () => {
    getList() // Refresh activity list after adding
    showAddDialog.value = false // Close the dialog
  }

  // onMounted(fetchActivities);
</script>

<style scoped>
  .header-tool {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }

  .header-tool button {
    margin-right: 5px;
  }
  .set-box {
    display: flex;
    justify-content: flex-start;
    align-items: center;
  }
  .input-number-set {
    margin: 0 20px;
  }
</style>
